<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Exchange_rate_import extends CI_Controller {
	protected $feedUrl;

	/**
	 * 
	 * The constructor
	 */
	function __construct() {
		parent::__construct();
		
		$this->feedUrl = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml';
		
		$this->load->model('currency_model');
		$this->load->model('exchange_rate_model');
	}	
	
	/**
	 * 
	 * The entry point of the import routine, it will controll the whole process
	 */
	public function start(){
		try {	
			if (ob_get_level() == 0){
				ob_start();			
			}
			//no time limit
			set_time_limit(0);
			
			$this->db->save_queries = false;
			
			//let's begin a transaction
			$this->db->trans_begin();
			
			echo 'A new exchange rate import transaction has been strated.<br />';
			
			//import queries
			self::process();	
			
			//everything was just fine so we can commit the transaction
			$this->db->trans_commit();
			
			echo 'The import routine was finished successfully.<br />';
			
			ob_end_flush();
		}
		catch (Exception $e) {
			//An exception has been thrown, we must rollback the transaction
		    $this->db->trans_rollback();
		    
		    show_error($e->getMessage() . '<br /> The transaction is rolling back...', 417);
		}		
		
	}
	
	private function process() {
    	$feed = simplexml_load_file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
    	$feedDate = (string) $feed->Cube->Cube['time'];
    	$this->exchange_rate_model->delete('date = "' . $feedDate . '"');
    	foreach($feed->Cube->Cube->Cube as $rate) {
    		$currencyObj = $this->currency_model->get_currency(htmlentities(trim($rate["currency"])));
    		if ($currencyObj) {		
				$this->exchange_rate_model->fields['currency'] = $currencyObj->id;
				$this->exchange_rate_model->fields['value'] = $rate["rate"];
				$this->exchange_rate_model->fields['date'] = $feedDate;
		
				$exchangeRateObj = $this->exchange_rate_model->fields_to_object();
				
				$exchangeRateObj->insert();        		
    		}
    	}
    	
    	//adding the EURO (default) currency = 1
    	$currencyObj = $this->currency_model->get_currency('EUR');
    	if ($currencyObj) {		
			$this->exchange_rate_model->fields['currency'] = $currencyObj->id;
			$this->exchange_rate_model->fields['value'] = 1;
			$this->exchange_rate_model->fields['date'] = $feedDate;
		
			$exchangeRateObj = $this->exchange_rate_model->fields_to_object();
				
			$exchangeRateObj->insert();    
    	}  	
	}
}